<?php
class ReportService extends BaseDbService
{
	private $searchService;
	
	public function __construct(){
		$this->searchService	= new SearchService();
		$this->dao		= new ReportDao();
	}
	
	public function getCountByDate($d)
	{
		$condition['where']['expression'] = 'pay_time <="'.$d.' 23:59:59" and pay_time>="'.$d.' 00:00:00" ';
	
		return $this->count($condition);
	}
	
	public function getReportList($uid, $start,$num)
	{
		if($uid>0)
		{
			$condition['where']['expression'] 			= 'outer_code = :outer_code';
			$condition['where']['value']['outer_code'] 	= $uid;
		}
		$condition['orderby'] 	= 'pay_time DESC';
		$result['count'] 		= $this->dao->count($condition);
		if($result['count']>0)
		{
			$condition['limit'] 	= $num;
			$condition['offset'] 	= $start;
			$result['rows'] 		= $this->dao->fetchRows($condition);
		}
		else
		{
			$result['rows'] 		= false;
		}
		
		return $result;
	}
	
	
	public function getTaoKeReportByPeriod($sessionKey, $startDate, $endDate)
	{
		$ret	= array();
		$du		= C('DateUtil');
		while($startDate<=$endDate)
		{
			$tmp		= $this->getTaoKeReportByDate($sessionKey, date('Ymd', strtotime($startDate)));
			if(!empty($tmp))
			{
				$ret	= array_merge($ret, $tmp);
			}
			$startDate	= date('Y-m-d', $du->dateAdd('d', 1, $startDate));
			usleep(200);
		}
		return $ret;
	}
	
	
	public function addReports($list)
	{
		$error		= false;
		$userDao	= new UserDao();
		$returnRate	= C('CommonFunction')->getReturnRate();
		foreach($list as $lv)
		{
			$lv['trade_id'] = sprintf('%.0f',$lv['trade_id']);
			if(!$this->dao->exists($lv['trade_id'],$lv['num_iid']))
			{
				if(!array_key_exists('created', $lv))
				{
					$lv['created']	= date('Y-m-d H:i:s');
				}
				$lv['iid']	= '';
				$id	= $this->dao->add($lv);
				if($id<=0)
				{
					$error	= true;
				}
				else
				{
					if($returnRate>0 && $lv['outer_code']>0)
					{
						$userDao->addMoney($lv['outer_code'],$lv['commission']*$returnRate/100);
					}
					C('ViewHistoryService')->updateViewHistory($lv['num_iid'],3,$lv['item_num']);
				}
			}
		}
		return !$error;
	}
	
	public function getTaoKeReportByDate($sessionKey, $dateStr, $fields=array())
	{
		$cols		= split(',','app_key,outer_code,trade_id,pay_time,pay_price,num_iid,item_title,item_num,category_id,category_name,shop_title,commission_rate,commission,iid,seller_nick,');
		$fields		= $this->checkFields($cols,$fields);
		
		$params			= array(
			'method' 	=> 'taobao.taobaoke.report.get',
			'fields' 	=> $fields,
			'date'		=> $dateStr,
			'session'	=> $sessionKey,
		);
		
		$apiSetting	= C('SettingService')->get('api_setting',true);
		$apiKey		= $apiSetting['taobao_api_appkey'];
		$keys		= explode(',', $apiKey);
		$num		= count($keys);
		$records	= array();
		$this->searchService->setSelectRandApi(false);
		for($i=0;$i<$num;$i++)
		{
			$this->searchService->setSelApi($i);
			$params['page_no']		= 1;
			$params['page_size']	= 40;
			while(true)
			{
				$tmp 		= $this->searchService->getResult($params);
				if(!$tmp || !array_key_exists('taobaoke_report_get_response', $tmp)){
					break;
				}
				
				$tmpRecords	= array_key_exists('taobaoke_report', $tmp['taobaoke_report_get_response'])?$tmp['taobaoke_report_get_response']['taobaoke_report']['taobaoke_report_members']['taobaoke_report_member']:false;
				if($tmpRecords!==false)
				{
					$records	= array_merge($records,$tmpRecords);
				}
				$totalRecords		= $tmp['taobaoke_report_get_response']['taobaoke_report']['total_results'];
				$totalPage			= intval(($totalRecords-1)/$params['page_size'])+1;
				if($params['page_no']>=$totalPage)
				{
					break;
				}
				$params['page_no']++;
			}
		}
		
		return $records;
	}
	
	private function checkFields($allow,$fields)
	{
		if(!empty($fileds))
		{
			$tmp	= array();
			foreach($fields as $f)
			{
				if(in_array($f, $allow))
				{
					$tmp[]	= $f;
				}
			}
			$fields	= $tmp;
		}
		if(empty($fileds))
		{
			$fields		= implode(',', $allow);
		}
		
		return $fields;
	}
	
	public function getTotalMoneyByPeriod($startDate='',$endDate='')
	{
		$condition['where']['expression']	= '1=1 ';
		if($startDate!='')
		{
			 $condition['where']['expression']	.= 'and pay_time >= "'.$startDate.' 00:00:00"';
		}
		if($endDate!='')
		{
			 $condition['where']['expression']	.= 'and pay_time <= "'.$endDate.' 23:59:59"';
		}
		$condition['fields'] 	= 'sum(commission) as money';
		$tmp 					= $this->dao->fetchRows($condition);
		if(empty($tmp[0]['money']))
		{
			return 0;
		}
		return $tmp[0]['money'];
	}
}
?>